//
//  YHYAFNetTool.m
//  Travels
//
//  Created by yanghuiyan on 16/3/7.
//  Copyright © 2016年 yanghuiyan. All rights reserved.
//

#import "YHYAFNetTool.h"
#import "AFNetworking.h"
#import "NSString+MD5.h"
@implementation YHYAFNetTool

+ (void)GETNetWirhUrl:(NSString *)url
                 body:(id)body
           headerFile:(NSDictionary *)header
             response:(YHYResponseStyle)responseStyle
              Success:(BlockOfSuccess)success
              Failure:(void (^)(NSError * error))failure{
    
   
    
    //1.设置网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.设置请求头
    if (header) {
        for (NSString *key in header.allKeys) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    }
    //3.设置返回数据的类型
    switch (responseStyle) {
            case YHYJSON:
                manager.responseSerializer = [AFJSONResponseSerializer serializer];
                break;
            case YHYXML:
                manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
                break;
            case YHYDATA:
                manager.responseSerializer = [AFHTTPResponseSerializer serializer];
                break;
            default:
                break;
        }
    
     
    //4.设置响应数据的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
        
    //5.UTF-8转码
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    
    // 获取路径
    NSString *path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    // 将网址md5格式转化 拼接路径
    NSString *cahcePath = [NSString stringWithFormat:@"%@/%@.plist", path, [url md5ForString]];
    
    //6.请求数据
    [manager GET:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
            success(responseObject);
//            if (responseObject) {
//            
//                success(responseObject);
                // 缓存
                [NSKeyedArchiver archiveRootObject:responseObject toFile:cahcePath];
                
//            }
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
//        if (error) {
//            failure(error);
            if (error) {
            
                // 若网络请求失败时 取出路径中对应的数据
                id responseObject = [NSKeyedUnarchiver unarchiveObjectWithFile:cahcePath];
                // 如果有数据 返回数据
                if (responseObject) {
                    success(responseObject);
                }
                failure(error);
            }
//        }
    }];
    
}

+ (void)POSTNetWirhUrl:(NSString *)url
                  body:(id)body
             bodyStyle:(YHYRequestStyle)bodyRequestStyle
            headerFile:(NSDictionary *)header
              response:(YHYResponseStyle)responseStyle
               Success:(BlockOfSuccess)success
               Failure:(void (^)(NSError * error))failure{
    
    //1.设置网络管理者
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    //2.设置body体数据类型
    switch (bodyRequestStyle) {
        case YHYRequestJSON:
            manager.requestSerializer = [AFJSONRequestSerializer serializer];
            break;
        case YHYRequestString:
            [manager.requestSerializer setQueryStringSerializationWithBlock:^NSString * _Nonnull(NSURLRequest * _Nonnull request, id  _Nonnull parameters, NSError * _Nullable * _Nullable error) {
                return parameters;
            }];
        default:
            break;
    }
    //3.设置请求头
    if (header) {
        for (NSString *key in header.allKeys) {
            [manager.requestSerializer setValue:header[key] forHTTPHeaderField:key];
        }
    //4.设置返回数据的类型
    switch (responseStyle) {
        case YHYJSON:
            manager.responseSerializer = [AFJSONResponseSerializer serializer];
            break;
        case YHYXML:
            manager.responseSerializer = [AFXMLParserResponseSerializer serializer];
            break;
        case YHYDATA:
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
            break;
            default:
            break;
        }
        
    //5.设置响应数据的类型
    [manager.responseSerializer setAcceptableContentTypes:[NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html",@"text/css",@"text/plain", @"application/javascript",@"image/jpeg", @"text/vnd.wap.wml", nil]];
        
    //6.UTF-8转码
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
    //7.请求数据
    [manager GET:url parameters:body progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        if (responseObject) {
                success(responseObject);
            }
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        if (error) {
                failure(error);
            }
        }];
    }
}

#pragma mark - 本地储存

+ (NSString *)createFilePathFromDocumentWithFolders:(NSArray<NSString *> *)folders fileName:(NSString *)fileName{
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
    NSString *finalPath = [NSString stringWithFormat:@"%@", document];
    for (NSString *folder in folders) {
        finalPath = [finalPath stringByAppendingPathComponent:folder];
    }
    
    [[NSFileManager defaultManager] createDirectoryAtPath:finalPath withIntermediateDirectories:YES attributes:nil error:nil];
    
    finalPath = [finalPath stringByAppendingPathComponent:fileName];
    return finalPath;
}

+ (BOOL)saveDataOnLocal:(NSData *)data localPath:(NSString *)path{
    
    return [data writeToFile:path atomically:YES];
}


@end
